package com.jthinker.blog.web.filter;

import com.jthinker.blog.bean.vo.Constant;
import com.jthinker.blog.bean.vo.UserWrapper;
import com.jthinker.blog.service.UserInfoService;
import com.jthinker.blog.util.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * User: Gang Chen
 * Date: 2015/8/5 19:23
 */
public class LoginFilter implements Filter
{
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginFilter.class);

    private UserInfoService userInfoService = SpringUtils.getBean(UserInfoService.class);

    private static final String LOGIN_URL = Constant.URL_ADMIN_PATH_PREFIX + Constant.URL_LOGIN;
    private static final String LOGOUT_URL = Constant.URL_ADMIN_PATH_PREFIX + Constant.URL_LOGOUT;

    private Set<String> passUrls;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {
        Set<String> sets = new HashSet<String>();
        sets.add(LOGIN_URL);
        sets.add(LOGOUT_URL);
        passUrls = Collections.unmodifiableSet(sets);

        LOGGER.info("pass urls {}", passUrls);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
    {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String relativeUrl = getRelativeUrl(request);

        if (isPassUrl(relativeUrl))
        {
            filterChain.doFilter(servletRequest, servletResponse);
        }
        else
        {
            UserWrapper wrapper = userInfoService.getCurrentUser(request);
            if (wrapper == null)
            {
                HttpServletResponse response = (HttpServletResponse) servletResponse;
                response.sendRedirect(request.getContextPath() + LOGIN_URL);
            }
            else
            {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy()
    {
        LOGGER.info("{} destory...", getClass());
    }

    private String getRelativeUrl(HttpServletRequest request)
    {
        String context = request.getContextPath();
        String fullUrl = request.getRequestURI();
        int index = fullUrl.contains(".") ? fullUrl.lastIndexOf(".") : fullUrl.length();
        return StringUtils.substring(fullUrl, context.length(), index);
    }

    private boolean isPassUrl(String url)
    {
        return passUrls.contains(url);
    }
}
